package com.eric.ztea.controller;

import com.eric.ztea.dao.SysUserRepository;
import com.eric.ztea.domain.SysUser;
import com.eric.ztea.utils.EhCacheUtils;
import com.eric.ztea.validate.RegisterValidate;
import com.eric.ztea.comm.AjaxResult;
import com.eric.ztea.utils.StringUtils;
import com.eric.ztea.utils.SMSUtils;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.jfinal.plugin.ehcache.CacheKit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;

@RestController
@RequestMapping("/ajax")
public class AjaxController  extends Controller {
    private Log logger=Log.getLog(AjaxController.class);
    private AjaxResult result = new AjaxResult();

    @Autowired
    SysUserRepository userRepository;

    CacheManager cacheManager;
    /**
     * 注册表单提交 ajax
     */
    @Before(RegisterValidate.class)
    @PostMapping("/register")
    public String register(String tel, String number,ModelMap modelMap) {
        logger.info("enter register func!");
        SysUser user = null;
        String msg;

        user = userRepository.findByTelephone(tel);
        //判断手机验证码是否正确
        boolean mobileCodeEquals = mobileCodeEquals(tel, number);
        if (!mobileCodeEquals) {
            logger.error("手机验证码输入错误，请重新输入");
            msg = "手机验证码输入错误，请重新输入";
            modelMap.put("msg", msg);
            return "login";
        }
//        String openId = getSessionAttr("openId");
        String openId = "fbisbfievus";
        // 判断手机是否存在
        if (null != user) {
            userRepository.notify();
        }
        else {
            user = new SysUser();
            user.setTelephone(tel);
            user.setOpenid(openId);
            userRepository.save(user);
        }
        logger.info("register finish！！！");
        return "home";
    }

    /**
     * 验证手机验证码是否正确
     * @param tel
     * @param code
     */
    private boolean mobileCodeEquals(String tel,String code){
        //判断手机验证码是否正确
//        Cache cache = cacheManager.getCache("tenMinute");
        Cache cache = EhCacheUtils.getInstance().get("tenMinute");
        if (null != cache)
        {
            System.out.println("find cache!");
        }
//        String cache_code = CacheKit.get("tenMinute", tel);
        String cache_code = (String)EhCacheUtils.getInstance().get("tenMinute", tel);
        System.out.println("cache_code:"+cache_code +"tel_code:"+code);
        if (null==cache_code || !code.equals(cache_code)) {
            return false;
        }else {
            //如果相同则移除该手机验证码缓存
//            CacheKit.remove("tenMinute", tel);
            EhCacheUtils.getInstance().remove("tenMinute",tel);
            return true;
        }
    }

    /**
     * 发送手机验证码并存入缓存
     * @param tel
     */
    @RequestMapping(value = "/sendSMS")
    public void sendSMSCode(@RequestParam(value = "tel", required = true)String tel){
//    private void sendSMSCode(String mobile,int smsType){
        String code=StringUtils.random(6, StringUtils.RandomType.INT);
        int res_code = -9;

        //注册
        res_code= SMSUtils.SMSCode(tel, code, null, null, null,null, SMSUtils.SendSMSType.REGISTER);

//        //找回密码
//        res_code= SMSUtils.SMSCode(tel, code, null, null, null,null,SMSUtils.SendSMSType.FORGET);

        if (res_code!=0) {
            renderJson(result.addError("短信验证码发送失败"));
            return;
        }
        //验证码放入缓存
        logger.info("短信验证码>>"+code);
        EhCacheUtils.getInstance().put("tenMinute",tel,code);
//        CacheKit.put("tenMinute", tel, code);
//        cacheManager.addCache("tenMinute");

//        renderJson(result);
    }
}
